/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice.BianQian.first;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.xcl.calculator.Ability.BianQian.BianQianShareAbility;
import com.xcl.calculator.DataANet.Sharmes;
import com.xcl.calculator.DataANet.Showmes;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import com.xcl.calculator.slice.BianQian.Contactor;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.IBundleManager;
import ohos.data.distributed.common.*;
import ohos.data.distributed.device.DeviceFilterStrategy;
import ohos.data.distributed.user.SingleKvStore;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.xcl.calculator.MyApplication.liteOrm;

/**
 * The type Bian qian share ability slice.
 *
 * @author Xcl
 * @date 2021 /1/12
 * @package com.xcl.calculator.slice.BianQian.first
 */
public class BianQianShareAbilitySlice extends AbilitySlice implements ContactProvider.AdapterClickListener, Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "BianQianShareAbilitySlice");
    /**
     * The constant STORE_ID.
     */
    private static final String STORE_ID = "contact_db1";
    /**
     * The constant text.
     */
    private static String text = null;
    /**
     * The constant text1.
     */
    private static String text1 = null;

    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;
    /**
     * The Contact adapter.
     */
    private ContactProvider contactAdapter;
    /**
     * The Contact arrays.
     */
    private List<Contactor> contactArrays;
    /**
     * The Kv manager.
     */
    private KvManager kvManager;
    /**
     * The Single kv store.
     */
    private SingleKvStore singleKvStore;

    /**
     * 分布式数据库1
     *
     * @param manager the manager
     * @return single kv store
     */
    private static SingleKvStore createDb(KvManager manager) {
        SingleKvStore kvStore = null;
        try {
            Options options = new Options();
            options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
            kvStore = manager.getKvStore(options, STORE_ID);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return kvStore;
    }

    /**
     * 删除
     */
    private static void delete1() {
        try {
            liteOrm.delete(new WhereBuilder(Sharmes.class)
                    .greaterThan("id", 0)
                    .and()
                    .lessThan("id", (Preference_RW.ff4_r() + 1)));
            Preference_RW.ff4_w(1);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 分享数据
     */
    private void sharedata() {
        try {
            //long book = liteOrm.queryCount(new QueryBuilder<Sharmes>(Sharmes.class));
            List<Sharmes> books = liteOrm.query(new QueryBuilder<Sharmes>(Sharmes.class)
                    .columns(new String[]{"id", "title", "message"})
                    .distinct(true)
                    .whereGreaterThan("id", 0)
                    .whereAppendAnd()
                    .whereLessThan("id", Preference_RW.ff4_r() + 1));
            for (int i = 0; i < books.size(); i++)
                BianQianShareAbilitySlice.this.writeData(books.get(i).getTitle(), books.get(i).getMessage());
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 开始
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_bianqian_0m);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_bianqian_0t);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }

            Component component1 = this.findComponentById(ResourceTable.Id_listContainer);
            component1.setBindStateChangedListener(new Component.BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    component.setTouchFocusable(true);
                    component.setVibrationEffectEnabled(true);
                    component.requestFocus();
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {
                }
            });
            this.findComponentById(ResourceTable.Id_bianqianmain0).setTouchEventListener(this);
            BianQianShareAbility bianQianShareAbility = (BianQianShareAbility) this.getAbility();
            bianQianShareAbility.setBianQianAbilitySlice(this);
            // 应用未被授予权限
            // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
            if (this.verifySelfPermission(ohos.security.SystemPermission.DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED)
                if (this.canRequestPermission(ohos.security.SystemPermission.DISTRIBUTED_DATASYNC))
                    this.requestPermissionsFromUser(
                            new String[]{ohos.security.SystemPermission.DISTRIBUTED_DATASYNC}, 20220109);
                else {
                    // 显示应用需要权限的理由，提示用户进入设置授权
                    this.ShowDialog("请进入系统设置进行授权后再使用此功能!");

                    /*无参--页面跳转开始*/
                    Intent intent1 = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.BianQian.BianQianShowAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent1.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent1);
                    /*页面跳转结束--无参*/
                    this.onBackPressed();
                }
            this.initDbManager();
            this.initList();
            this.sharedata();
            this.getUITaskDispatcher().delayDispatch(this::queryContact, 100L);
            this.findComponentById(ResourceTable.Id_addContact).setClickedListener(new Component.ClickedListener() {
                private void result(String titles, String messages) {
                    BianQianShareAbilitySlice.this.writeData(messages, titles);
                    BianQianShareAbilitySlice.this.contactArrays.add(new Contactor(titles, messages));
                    BianQianShareAbilitySlice.this.contactAdapter.notifyDataSetItemInserted(BianQianShareAbilitySlice.this.contactAdapter.getCount());
                    BianQianShareAbilitySlice.this.queryContact();
                }

                @Override
                public void onClick(Component component) {
                    BianQianShareAbilitySlice.this.
                            showDialog(null, null, this::result);
                }
            });
            this.findComponentById(ResourceTable.Id_sync).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    try {
                        List<ohos.data.distributed.device.DeviceInfo> deviceInfoList = BianQianShareAbilitySlice.this.kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER);
                        List<String> deviceIdList = new ArrayList<>(0);
                        for (ohos.data.distributed.device.DeviceInfo deviceInfo : deviceInfoList)
                            deviceIdList.add(deviceInfo.getId());
                        if (deviceIdList.size() == 0) {
                            BianQianShareAbilitySlice.this.ShowDialog("同步失败,请确认您的设备均在线!");
                            return;
                        }
                        BianQianShareAbilitySlice.this.singleKvStore.registerSyncCallback(new SyncCallback() {
                            @Override
                            public void syncCompleted(Map<String, Integer> map) {
                                BianQianShareAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                    @Override
                                    public void run() {
                                        XLog.info(BianQianShareAbilitySlice.label, "sync success");
                                        BianQianShareAbilitySlice.this.queryContact();
                                        BianQianShareAbilitySlice.this.ShowDialog1("同步成功");
                                    }
                                });
                                BianQianShareAbilitySlice.this.singleKvStore.unRegisterSyncCallback();
                            }
                        });
                        BianQianShareAbilitySlice.this.singleKvStore.sync(deviceIdList, SyncMode.PUSH_PULL);
                    } catch (Exception e) {
                        XLog.error(BianQianShareAbilitySlice.label, e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 下方数据展示1
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_extoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_extoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 下方数据展示2
     *
     * @param text1 the text 1
     */
    private void ShowDialog1(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 初始化列表
     */
    private void initList() {
        try {
            Component component = this.findComponentById(ResourceTable.Id_listContainer);
            ListContainer listContainer;
            if (component instanceof ListContainer) {
                listContainer = (ListContainer) component;
                this.contactArrays = new ArrayList<>(0);
                this.contactAdapter = new ContactProvider(this, this.contactArrays);
                listContainer.setItemProvider(this.contactAdapter);
                listContainer.enableScrollBar(Component.AXIS_Y, true);
                listContainer.setScrollbarRoundRect(true);
                listContainer.setScrollbarRadius(component.getScrollbarThickness() / 2);
                this.contactAdapter.setAdapterClickListener(this);
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 初始化分布式数据库
     */
    private void initDbManager() {
        try {
            this.kvManager = this.createManager();
            this.singleKvStore = BianQianShareAbilitySlice.createDb(this.kvManager);
            KvStoreObserver kvStoreObserverClient = new KvStoreObserverClient();
            SingleKvStore kvStore = this.singleKvStore;
            kvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_REMOTE, kvStoreObserverClient);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 创建分布式数据库
     *
     * @return kv manager
     */
    private KvManager createManager() {
        KvManager manager = null;
        try {
            KvManagerConfig config = new KvManagerConfig(this);
            manager = KvManagerFactory.getInstance().createKvManager(config);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return manager;
    }

    /**
     * 分布式数据库1插入数据
     */
    private void queryContact() {
        try {
            List<Entry> entryList = this.singleKvStore.getEntries("");
            this.contactArrays.clear();
            try {
                for (Entry entry : entryList)
                    this.contactArrays.add(new Contactor(entry.getValue().getString(), entry.getKey()));
            } catch (Exception e) {
                XLog.error(label, e.getMessage());
            }
            this.contactAdapter.notifyDataChanged();
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }


    /**
     * 分布式数据库插入值
     *
     * @param key   the key
     * @param value the value
     */
    private void writeData(String key, String value) {
        if (key == null || key.isEmpty() || value == null || value.isEmpty()) return;
        try {
            this.singleKvStore.putString(key, value);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 分布式数据库删除数据
     *
     * @param key the key
     */
    private void deleteData(String key) {
        if (key.isEmpty()) return;
        try {
            this.singleKvStore.delete(key);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 下方数据展示
     *
     * @param titles         the titles
     * @param messages       the messages
     * @param dialogCallBack the dialog call back
     */
    private void showDialog(String titles, String messages, ContactComponent.DialogCallBack dialogCallBack) {
        try {
            CommonDialog commonDialog = new CommonDialog(this);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int device = Integer.parseInt(localDeviceInfo.getType());
            ContactComponent component = new ContactComponent(this, device);
            component.initData(titles, messages);
            component.setDialogCallBack(new ContactComponent.DialogCallBack() {
                @Override
                public void result(String titlesInput, String messagesInput) {
                    component.setTextFiledNormalGraphic();
                    if (titlesInput.isEmpty() || titlesInput.trim().isEmpty()) {
                        BianQianShareAbilitySlice.this.ShowDialog("标题必填");
                        component.setTextFiledErrorGraphic(1);
                        return;
                    }

                    if (messagesInput.isEmpty() || messagesInput.trim().isEmpty()) {
                        BianQianShareAbilitySlice.this.ShowDialog("信息必填");
                        component.setTextFiledErrorGraphic(2);
                        return;
                    }

                    if (messages == null && BianQianShareAbilitySlice.this.messagesIsExist(messagesInput)) {
                        BianQianShareAbilitySlice.this.ShowDialog("标题已经存在了");
                        component.setTextFiledErrorGraphic(2);
                        return;
                    }

                    if (dialogCallBack != null) dialogCallBack.result(titlesInput, messagesInput);
                    commonDialog.remove();
                }
            });
            commonDialog.setAutoClosable(true);
            commonDialog.setContentCustomComponent(component);
            commonDialog.show();
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 分布式数据库2
     *
     * @param messages the messages
     * @return boolean boolean
     */
    private boolean messagesIsExist(String messages) {
        List<Entry> entryList = this.singleKvStore.getEntries("");
        for (Entry entry : entryList) if (entry.getKey().equals(messages)) return true;
        return false;
    }

    /**
     * 编辑数据
     *
     * @param position the position
     */
    @Override
    public void edit(int position) {
        try {
            Contactor contactor = this.contactArrays.get(position);
            this.showDialog(contactor.getTitles(), contactor.getMessages(), new ContactComponent.DialogCallBack() {
                @Override
                public void result(String titles, String messages) {
                    BianQianShareAbilitySlice.this.writeData(messages, titles);
                    BianQianShareAbilitySlice.this.contactArrays.set(position, new Contactor(titles, messages));
                    BianQianShareAbilitySlice.this.contactAdapter.notifyDataSetItemChanged(position);
                    BianQianShareAbilitySlice.this.queryContact();
                    BianQianShareAbilitySlice.this.ShowDialog1("编辑成功");
                }
            });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 删除数据
     *
     * @param position the position
     */
    @Override
    public void delete(int position) {
        try {
            CommonDialog commonDialog = new CommonDialog(this);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                Component component = LayoutScatter.getInstance(this.getContext())
                        .parse(ResourceTable.Layout_bianqian_3m, null, true);
                commonDialog.setAutoClosable(true);
                commonDialog.setSize(600, 600);
                commonDialog.setContentCustomComponent(component);
                component.findComponentById(ResourceTable.Id_bqsure).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        if (position > BianQianShareAbilitySlice.this.contactArrays.size() - 1) {
                            BianQianShareAbilitySlice.this.ShowDialog("要删除的元素不存在");
                            return;
                        }
                        BianQianShareAbilitySlice.this.deleteData(BianQianShareAbilitySlice.this.contactArrays.get(position).getMessages());
                        BianQianShareAbilitySlice.this.contactArrays.remove(position);
                        BianQianShareAbilitySlice.this.contactAdapter.notifyDataChanged();
                        BianQianShareAbilitySlice.this.ShowDialog1("删除成功");
                        commonDialog.destroy();
                    }
                });
                component.findComponentById(ResourceTable.Id_bqcancel).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        commonDialog.destroy();
                    }
                });
                commonDialog.show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                Component component = LayoutScatter.getInstance(this.getContext())
                        .parse(ResourceTable.Layout_bianqian_3m, null, true);
                commonDialog.setAutoClosable(true);
                commonDialog.setSize(600, 600);
                commonDialog.setContentCustomComponent(component);
                component.findComponentById(ResourceTable.Id_bqsure).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        if (position > BianQianShareAbilitySlice.this.contactArrays.size() - 1) {
                            BianQianShareAbilitySlice.this.ShowDialog("要删除的元素不存在");
                            return;
                        }
                        BianQianShareAbilitySlice.this.deleteData(BianQianShareAbilitySlice.this.contactArrays.get(position).getMessages());
                        BianQianShareAbilitySlice.this.contactArrays.remove(position);
                        BianQianShareAbilitySlice.this.contactAdapter.notifyDataChanged();
                        BianQianShareAbilitySlice.this.ShowDialog1("删除成功");
                        commonDialog.destroy();
                    }
                });
                component.findComponentById(ResourceTable.Id_bqcancel).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        commonDialog.destroy();
                    }
                });
                commonDialog.show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 后台1
     */
    @Override
    public void onBackPressed() {
        try {
            this.kvManager.closeKvStore(this.singleKvStore);
            this.kvManager.deleteKvStore(STORE_ID);
            BianQianShareAbilitySlice.delete1();
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        super.onBackPressed();
        this.terminateAbility();
    }

    /**
     * 进入后台·
     *
     * @param intent

     @Override public void onForeground(Intent intent) {
     this.onBackPressed();
     delete1();
     super.onForeground(intent);
     }*/

    /**
     * 展示数据
     *
     * @param position the position
     */
    @Override
    public void show(int position) {
        try {
            Contactor contactor = this.contactArrays.get(position);
            CommonDialog commonDialog = new CommonDialog(this);

            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                Component component = LayoutScatter.getInstance(this.getContext())
                        .parse(ResourceTable.Layout_bianqian_4m, null, true);
                commonDialog.setSize(950, 950);
                commonDialog.setContentCustomComponent(component);
                Text text1 = (Text) component.findComponentById(ResourceTable.Id_bqtext1);
                Text text2 = (Text) component.findComponentById(ResourceTable.Id_bqtext2);
                text2.setText(contactor.getTitles());
                text1.setText(contactor.getMessages());
                component.findComponentById(ResourceTable.Id_bqsure1).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        commonDialog.destroy();
                    }
                });
                commonDialog.show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                Component component = LayoutScatter.getInstance(this.getContext())
                        .parse(ResourceTable.Layout_bianqian_4t, null, true);
                commonDialog.setSize(1000, 1000);
                commonDialog.setContentCustomComponent(component);
                Text text1 = (Text) component.findComponentById(ResourceTable.Id_bqtext1);
                Text text2 = (Text) component.findComponentById(ResourceTable.Id_bqtext2);
                text2.setText(contactor.getTitles());
                text1.setText(contactor.getMessages());
                component.findComponentById(ResourceTable.Id_bqsure1).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        commonDialog.destroy();
                    }
                });
                commonDialog.show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 保存数据
     *
     * @param position the position
     */
    @Override
    public void save(int position) {
        try {
            Contactor contactor = this.contactArrays.get(position);
            List<Showmes> books = liteOrm.query(new QueryBuilder<Showmes>(Showmes.class)
                    .columns(new String[]{"id", "title", "message"})
                    .distinct(true)
                    .whereEquals("title", contactor.getMessages()));
            if (books.size() == 0) {
                long a1 = Preference_RW.ff3_r();
                Showmes s1 = new Showmes();
                s1.setId(a1 + 1);
                s1.setTitle(contactor.getMessages());
                s1.setMessage(contactor.getTitles());
                liteOrm.save(s1);
                Preference_RW.ff3_w(a1 + 2);
            } else {
                Showmes s1 = new Showmes();
                s1.setId(books.get(0).getId());
                s1.setTitle(contactor.getMessages());
                s1.setMessage(contactor.getTitles());
                liteOrm.save(s1);
            }
            this.ShowDialog1("保存成功");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 退出
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return boolean boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog1("程序退出成功，感谢您的使用!");
            try {
                this.kvManager.closeKvStore(this.singleKvStore);
                this.kvManager.deleteKvStore(STORE_ID);
                BianQianShareAbilitySlice.delete1();
            } catch (Exception e) {
                XLog.error(label, e.getMessage());
            }
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            ohos.global.resource.ResourceManager resManager = this.getResourceManager();
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            try {
                text = resManager.getElement(ResourceTable.String_titles).getString();
                text1 = resManager.getElement(ResourceTable.String_titlex).getString();
            } catch (Exception e) {
                XLog.error(label, e.getMessage());
            }
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 167) {
                    final String text2 = "到头了...";
                    if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                        new MyToastDialog(this.getContext(), text2, ResourceTable.Graphic_xtoast_framem, 40, 25)
                                .setDuration(120)
                                .setAlignment(LayoutAlignment.BOTTOM)
                                .setOffset(0, 100)
                                .show();
                        XLog.info(label, "当前设备类型为手机");
                    } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                        new MyToastDialog(this.getContext(), text2, ResourceTable.Graphic_xtoast_framet, 48, 37)
                                .setDuration(120)
                                .setAlignment(LayoutAlignment.BOTTOM)
                                .setOffset(0, 100)
                                .show();
                        XLog.info(label, "当前设备类型为平板");
                    } else {
                        XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                        this.terminateAbility();
                    }
                    XLog.info(label, "左滑了");
                } else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 167) {
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.BianQian.BianQianShowAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    try {
                        this.kvManager.closeKvStore(this.singleKvStore);
                        this.kvManager.deleteKvStore(STORE_ID);
                        BianQianShareAbilitySlice.delete1();
                    } catch (Exception e) {
                        XLog.error(label, e.getMessage());
                    }
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "右滑了");
                } else if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 167)
                    XLog.info(label, "上滑了");
                else if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 167)
                    XLog.info(label, "下滑了");
                else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }

    /**
     * 分布式数据库同步
     */
    private class KvStoreObserverClient implements KvStoreObserver {
        /**
         * On change.
         *
         * @param notification the notification
         */
        @Override
        public void onChange(ChangeNotification notification) {
            try {
                BianQianShareAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        XLog.info(BianQianShareAbilitySlice.label, "come to auto sync");
                        BianQianShareAbilitySlice.this.queryContact();
                        List<ohos.data.distributed.device.DeviceInfo> deviceInfoList = BianQianShareAbilitySlice.this.kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER);
                        List<String> deviceIdList = new ArrayList<>(0);
                        for (ohos.data.distributed.device.DeviceInfo deviceInfo : deviceInfoList) {
                            deviceIdList.add(deviceInfo.getId());
                            XLog.info(BianQianShareAbilitySlice.label, "deviceInfo = " + deviceInfo.getId());
                        }
                        BianQianShareAbilitySlice.this.ShowDialog1("共" + (deviceIdList.size() + 1) + "台设备，自动同步成功");
                    }
                });
            } catch (Exception e) {
                AGConnectCrash.getInstance().recordException(e);
                XLog.error(BianQianShareAbilitySlice.label, e.getMessage());
            }
        }
    }

}
